package hip.util.poi;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * @author qiujl
 * @date 2016-4-2
 * @describe 文件操作
 */

public class UploadFile {
    public static Logger logger = Logger.getLogger(UploadFile.class);

    public static String uploadFile(HttpServletRequest request, HttpServletResponse response, String filename) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile(filename);
        String sourceName = multipartFile.getOriginalFilename(); // 原始文件名
        String fileType = sourceName.substring(sourceName.lastIndexOf("."));

        logger.info("上传的文件名为:" + sourceName + "类型为:" + fileType);
        String base = request.getSession().getServletContext().getRealPath("/") + "attachments" + File.separator + "uploadedExcel";
        File file = new File(base);
        if (!file.exists()) {
            file.mkdirs();
        }

        response.setContentType("text/json; charset=UTF-8");
        String path = base + File.separator + sourceName;
        multipartFile.transferTo(new File(path));
        return path;
    }

    public static void removeFile(String path) {
        File f = new File(path);
        if (f.exists() && f.isDirectory()) {//判断是文件还是目录
            if (Objects.requireNonNull(f.listFiles()).length == 0) {//若目录下没有文件则直接删除
                f.delete();
            } else {//若有则把文件放进数组，并判断是否有下级目录
                File delFile[] = f.listFiles();
                int i = f.listFiles().length;
                for (int j = 0; j < i; j++) {
                    assert delFile != null;
                    if (delFile[j].isDirectory()) {
                        removeFile(delFile[j].getAbsolutePath());//递归调用del方法并取得子目录路径
                    }
                    delFile[j].delete();//删除文件
                }
            }
        } else if (f.exists() && f.isFile()) {
            f.delete();
        }
    }
}
